<template>
  <el-drawer
    v-model="isOpen"
    @close="close"
    :z-index="10"
    :modal="false"
    :lock-scroll="false"
    direction="rtl"
  >
    <template #header>
      <h4>导入</h4>
    </template>
    <template #default>
      <!--文件上传-->
      <el-upload
        style="width: 400px"
        list-type="text"
        v-model:file-list="fileList"
        :action="uploadUrl()"
        :headers="{ gridId: props.gridId, token }"
        :on-preview="filePreview"
        :on-remove="fileRemove"
        :limit="1"
        :on-exceed="fileExceed"
        :before-upload="beforeUpload"
        :on-success="successUpload"
        ref="uploadRef"
      >
        <el-button type="primary">上传</el-button>
        <template #tip>
          <el-link
            @click="importExcelTemplateDownload()"
            target="_blank"
            style="margin-left: 10px"
            type="primary"
            >模版下载</el-link
          >
          <div class="el-upload__tip">
            类型限制
            <span style="font-weight: bold">xlsx</span> | 大小限制
            <span style="font-weight: bold">{{ importJson.size }} KB</span> | 数据限制
            <span style="font-weight: bold">{{ importJson.num }} 条</span>
          </div>
        </template>
      </el-upload>
      <!--导入结果列表-->
      <el-table :data="uploadResults" size="small" border stripe style="width: 100%">
        <el-table-column label="上传文件" align="center">
          <template #default="scope">
            <el-link :href="scope.row.importFileUrl" target="_blank" type="primary">{{
              scope.row.importFileUrl.split('/').pop()
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="校验结果文件" align="center">
          <template #default="scope">
            <el-link
              v-if="scope.row.checkResult === 0"
              :href="scope.row.checkFileUrl"
              target="_blank"
              type="primary"
              >{{ scope.row.checkFileUrl.split('/').pop() }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="校验结果" align="center" width="80">
          <template #default="scope">
            {{ scope.row.checkResult === 1 ? '通过' : '不通过' }}
          </template>
        </el-table-column>
        <el-table-column label="导入结果" align="center" width="80">
          <template #default="scope">
            {{ scope.row.importResult === 1 ? '已导入' : '未导入' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" align="center" label="上传时间" width="150" />
      </el-table>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="confirmClick">导入数据</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup>
import { ref, computed, onBeforeMount } from 'vue'
import { ElMessage } from 'element-plus'
const token = sessionStorage.getItem('token')
const isOpen = ref(true)
// 编辑成功事件/通知父组件刷新
const emit = defineEmits(['editOk']) // 获取配置
const props = defineProps(['importJson', 'requestApi', 'gridId'])
// 解除与 editJson 双向绑定，改为单向
const importJson = computed(() => JSON.parse(JSON.stringify(props.importJson)))
const requestApi = props.requestApi
const fileList = ref([])
// 上传结果列表
const uploadResults = ref([])
const uploadRef = ref()
// const importJson = ref({
//   size: 100,
//   num: 1,
//   fields: [
//     {
//       isShow: true,
//       field: 'default',
//       alias: '别名',
//       gridField: null, // 绑定网格字段
//       rule: { required: true }
//     }
//   ]
// })

jsonEdit()

function jsonEdit() {}
// 文件删除
function fileRemove(file, uploadFiles) {
  console.log('文件删除', file, uploadFiles)
}
// 文件预览
function filePreview(uploadFile) {
  window.open(uploadFile.response.data.importFileUrl, '_blank')
}
// 文件超出限制
function fileExceed(files, uploadFiles) {
  ElMessage.warning(`只允许上传 1 个文件`)
}
// 文件上传检查
function beforeUpload(file) {
  const sizeKb = (file.size / 1024).toFixed(2)
  if (sizeKb > importJson.value.size) {
    ElMessage.warning(`上传的文件 ${sizeKb}/KB 超出文件大小限制 ${importJson.value.size}/KB`)
    return false
  }
  const fileType = file.name.split('.').pop()
  if (fileType != 'xlsx') {
    ElMessage.warning(`只允许上传 xlsx`)
    return false
  }
}
// 文件上传成功，返回参数校验结果
function successUpload(response, uploadFile, uploadFiles) {
  // 上传失败清空文件列表
  if (response.code != 200) {
    uploadRef.value.clearFiles()
    ElMessage.warning(response.msg)
    return
  } else if (response.data.checkResult === 0) {
    uploadRef.value.clearFiles()
  }
  uploadResults.value.push(response.data)
  console.log(response, uploadFile, uploadFiles)
}

// 关闭
function close() {
  emit('close')
}
// 提交
function confirmClick() {
  if (fileList.value.length === 0) {
    ElMessage.warning(`未上传导入文件`)
    return
  }
  importExcelData(fileList.value[0].response.data.id)
}

// 获取表格上传地址
function uploadUrl() {
  return requestApi.importExcel()
}

/**
 * 下载模版
 */
function importExcelTemplateDownload() {
  requestApi.importExcelTemplateDownload(props.gridId)
}

/**
 * 导入数据
 */
function importExcelData(importRecordId) {
  requestApi.importExcelData(importRecordId).then((data) => {
    if (data && data.code === 200) {
      ElMessage({
        message: '导入成功',
        type: 'success'
      })
      fileList.value[0].response.data.importResult = 1
      // 通知父组件刷新数据
      emit('editOk')
      // 关闭编辑页面
      // close()
    }
  })
}
</script>
<style scoped>
.el-link {
  font-size: 12px;
}
</style>
